package zero.tech.games.log.shareding;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import zero.tech.games.entity.log.TableCreater;
import zero.tech.games.log.mapper.TableCreaterMapper;

@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class DynamicCreateTableSharding implements ApplicationRunner{
	@Autowired
	private TableCreaterMapper tableCreaterMapper;
	public void createTables() {
		List<TableCreater> creaters=tableCreaterMapper.loadAll();
		for(TableCreater creater:creaters) {
			String dbname=creater.getDbname();;
			String tableprefix=creater.getTableprefix();
			int yearLowpoint=creater.getYearLowpoint();
			int yearUppoint=creater.getYearUppoint();
			int monthLowpoint=creater.getMonthLowpoint();
			int monthUppoint=creater.getMonthUppoint();
			String tmp_sql=creater.getCreate_sql();
			String sql="";
			List<String> targets=new ArrayList<String>();
			for(int i=yearLowpoint;i<=yearUppoint;i++) {
				for(int j=monthLowpoint;j<=monthUppoint;j++) {
					String table=tableprefix+"_"+i+"_"+j;
					targets.add(table);
					sql+=" SELECT table_name FROM information_schema.tables WHERE table_schema='"+dbname+"' and table_name='"+table+"' union all ";
				}
			}
			if(StringUtils.isNotEmpty(sql)) {
				sql=sql.substring(0, sql.length()-" union all ".length());
				System.out.println("targets:"+targets);
				System.out.println("sql:"+sql);
				List<String> tables=tableCreaterMapper.selectTables(sql);
				List<String> creates=new ArrayList<String>();
				for(String target:targets) {
					if(!tables.contains(target)) {
						//需要创建表
						creates.add(target);
					}
				}
				System.out.println("creates:"+creates);
				if(!creates.isEmpty()) {
					for(String table:creates) {
						String create_sql = tmp_sql.replace("$T", table);
						tableCreaterMapper.createTable(create_sql);
					}
				}
			}
		}
	}
	@Override
	public void run(ApplicationArguments args) throws Exception {
		this.createTables();
	}
}
